import React from 'react';
import Taro from '@tarojs/taro';

import {connect} from 'react-redux';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';

import {View, Image} from '@tarojs/components';
import StrategyModal from './components/StrategyModal/StrategyModal';
import DailyExclusiveModal from './components/DailyExclusiveModal/DailyExclusiveModal';
import TaskModal from './components/TaskModal/TaskModal';
import MemberModal from './components/MemberModal/MemberModal';
import RankingModal from './components/RankingModal/RankingModal';
import PropModal from './components/PropModal/PropModal';
import AdvModal from '@/pages/common/adv-modal/adv-modal';

import {
  GAME_SHARE_TITLE,
  OSS_BASE_PATH_PREFIX,
  OSS_PATH_PREFIX,
  TASK_CONDITION_TYPE,
  CODE_SUCCESS,
  PROP_TYPE,
  GOLD_SELECT_TASK,
} from './constant';
import './index.less';
import {handleUrl, fetchModal, setModalShow} from 'wmkit';

actions().actions.loadReducer();

// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class GoldCoinsIndexPa extends React.Component<Partial<T.IProps>, any> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      query: {},
      pics: {
        gameShareIcon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png', // 分享至朋友圈
        gameShareThum: OSS_BASE_PATH_PREFIX + '/gameShareThum.png', // 分享缩略图
        titleBj: OSS_PATH_PREFIX + '/titleBj.png',
        startGame: OSS_PATH_PREFIX + '/startGame.png',
        gameTimesShow: OSS_PATH_PREFIX + '/gameTimesShow.png',
        taskIcon: OSS_BASE_PATH_PREFIX + '/giftIcon.png', // 领福利
        exchangeIcon: OSS_PATH_PREFIX + '/exchangeIcon.png', // 兑好礼
        rankingIcon: OSS_PATH_PREFIX + '/rankingIcon.png',
        jindou: OSS_PATH_PREFIX + '/jindou.png',
        propBuffIcon: OSS_BASE_PATH_PREFIX + '/propBuffIcon.png', // 道具图标
      },

      // 模态框显示
      modal: {
        type: '', // 多个模态框
        visible: false,
        item: null,
      },
      selectedProp: null, // 使用道具

      // 广告
      adModal: {
        isModalFlag: false,
        imgUrl: '',
        jumpPage: {},
        nextPopupId: '',
        type: 'coinRainHome',
      },
    };
  }

  componentDidShow() {
    this.handleGetRouterParams(); // 获取路由参数
    this.props.actions.init();
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  componentWillReceiveProps(nextProps, nextContext: any): void {
    // 查询每日游戏次数如果有信息，则不进行弹框提示
    if (nextProps.main.status.loadingGameDaily == false && this.props.main.status.loadingGameDaily == true) {
      if (nextProps.main.response.loadGameDaily == CODE_SUCCESS) {
        console.log('今日领取记录');
        // 无信息则弹出开心收下弹框
        if (!nextProps.main.gameReceiveInfo.id) {
          this.handleModalShowAndHide('dailyExclusive', true);
        } else {
          this.handleModalShowAndHide('', false);
        }
      }
      this.handleGameAvailableTimes(); // 获取游戏次数
    }

    // 做任务
    if (nextProps.main.status.computingTask == false && this.props.main.status.computingTask == true) {
      if (nextProps.main.response.computedTask == CODE_SUCCESS) {
        this.handleTaskSuccess();
      }
    }

    // 查询榜单
    if (nextProps.main.status.loadingRanking == false && this.props.main.status.loadingRanking == true) {
      if (nextProps.main.response.loadRank == CODE_SUCCESS) {
        console.log('index.tsx 弹出榜单');
        this.handleModalShowAndHide('ranking', true);
      }
    }
  }

  /**
   * 获取路由参数
   */
  handleGetRouterParams = () => {
    let params = Taro.getCurrentInstance()?.router?.params;
    console.log('index.tsx handleGetRouterParams', params);
    if (params.favorite || params.share) {
      Taro.redirectTo({
        url: '/pages/package-I/home/index',
      });
      return;
    }

    // 判断上一级是哪个页面，如果是合卡或者是我的卡库页面，则从缓存里取id
    const pages = Taro.getCurrentPages();
    let currPage = pages[pages.length - 1];
    let showReferpagepath = currPage.__displayReporter.showReferpagepath;

    if (params && params.taskConditionsType && params.taskId) {
      // 如果是从游戏里返回的，或者是游戏里点击兑换中心再退回来的
      if (
        showReferpagepath == 'pages/package-I/receiveGoldCoins/index.html' ||
        showReferpagepath == 'pages/package-I/goldCoinsExchange/index.html'
      ) {
        let selectTask = Taro.getStorageSync(GOLD_SELECT_TASK);
        console.log('index.tsx goldIndex selectTask', selectTask);
        if (!selectTask) {
          Taro.removeStorageSync(GOLD_SELECT_TASK);
        } else {
          Taro.setStorageSync(GOLD_SELECT_TASK, {
            taskConditionsType: params.taskConditionsType,
            taskId: params.taskId,
          });
        }
      } else {
        Taro.setStorageSync(GOLD_SELECT_TASK, {
          taskConditionsType: params.taskConditionsType,
          taskId: params.taskId,
        });
      }
    } else {
      if (
        showReferpagepath != 'pages/package-I/receiveGoldCoins/index.html' &&
        showReferpagepath != 'pages/package-I/goldCoinsExchange/index.html' &&
        showReferpagepath != 'pages/package-I/goldCoinsDetail/index.html'
      ) {
        Taro.removeStorageSync(GOLD_SELECT_TASK);
      }
    }

    this.setState({
      query: {
        ...params,
      },
    });
    this.handleAdModalUpdateStatus(''); // 广告弹出
    this.handleQuery();
  };

  /**
   * 查询信息
   */
  handleQuery = () => {
    this.handleQueryGiveGameTimes(); // 新人赠送次数
    this.handleQueryUserInfo(); // 查询用户信息
    this.handleQueryPropItems({}); // 查询道具列表
    this.handleQueryGameInfo(); // 查询游戏信息
    this.handleQueryTaskItems({}); // 查询游戏任务列表
    // this.handleQueryRankingItems(); // 查询排行版内容
  };

  /**
   * 查询当日游戏
   */
  handleQueryDailyGameTimes = () => {
    this.props.actions.action.loadGameDailyTimes();
  };

  /**
   * 做任务的回调处理
   */
  handleTaskSuccess = () => {
    this.handleQueryPropItems({pageNum: 0}); // 查询道具列表
    this.handleQueryUserInfo(); // 查询用户信息
    this.handleGameAvailableTimes(); // 游戏次数
  };

  /**
   * 赠送游戏次数
   */
  handleQueryGiveGameTimes = () => {
    let params = {};
    this.props.actions.action.giveUserNoVipGameTimes();
  };

  /**
   * 查询游戏的物品信息
   */
  handleQueryGameGrticleInfo = () => {
    console.log('查询游戏物品信息');
    let params = {};
    this.props.actions.action.loadGameGrticleInfo(params);
  };

  /**
   * 查询会员信息
   */
  handleQueryUserInfo = () => {
    let params = {};
    this.props.actions.action.loadUserInfo(params);
  };

  /**
   * 查询用户的已用游戏次数（判断是否是新人）
   */
  handleQueryUserComputedGameTimes = () => {
    let params = {};
    this.props.actions.action.loadUserComputedGameTimes(params);
  };

  /**
   * 查询游戏信息
   */
  handleQueryGameInfo = () => {
    let params = {};
    this.props.actions.action.loadGameInfo(params);
  };

  /**
   * 查询道具信息
   */
  handleQueryPropItems = (pagation) => {
    const {
      main: {
        prop: {page},
      },
    } = this.props;
    let params = {
      ...page,
      ...pagation,
    };
    this.props.actions.action.loadPropItems(params);
  };

  /**
   * 查询每日领取次数
   */
  handleQueryGameTimesDaily = (type) => {
    console.log('index.tsx handleQueryGameTimesDaily type', type);
    let params = {
      delFlag: type,
    };
    this.props.actions.action.loadGameTimesDaily(params);
  };

  /**
   * 获取用户可用游戏次数限制
   */
  handleGameAvailableTimes = () => {
    let params = {};
    this.props.actions.action.loadGameTimes(params);
  };

  /**
   * 查询游戏任务列表
   */
  handleQueryTaskItems = (pagation) => {
    // 编辑参数
    const {
      main: {
        task: {page},
      },
    } = this.props;
    let params = {
      ...page,
      ...pagation,
    };
    this.props.actions.action.loadTaskItems(params);
  };

  /**
   * 查询排行榜单列表
   */
  handleQueryRankingItems = () => {
    let params = {};
    this.props.actions.action.loadRankingItems(params);
  };

  /**
   * 渲染内容
   * @returns
   */
  render() {
    if (!this.props.main) return null;
    let {
      main: {isLoading},
    } = this.props;
    console.log(isLoading);

    return (
      <View className="pageGoldCoinsIndexPa" catchMove>
        {this.renderHeader()}
        <View className="goldCoinsContent">
          {this.renderTitleBj()}
          {this.renderStartGame()}
          {this.renderMemberModal()}
          {this.renderTaskModal()}
          {this.renderStrategyModal()}
          {this.renderRankingModal()}
          {this.renderDailyExclusiveModal()}
          {this.renderPropModal()}
          {this.renderAdvModal()}
        </View>
      </View>
    );
  }

  /**
   * 渲染顶部内容（魔力豆 + 欧气攻略）
   * @returns
   */
  renderHeader() {
    const {pics} = this.state;
    const {
      main: {userInfo},
    } = this.props;
    console.log('index.tsx renderHeader userInfo', userInfo);
    return (
      <View className="header">
        <View className="magicBean">
          <Image src={pics.jindou} className="magicIcon" />
          <View className="magicNum">{userInfo.magicBean}</View>
        </View>
        <View className="strategy" onClick={this.handleStrategyModalShow}>
          <View className="strategyExtra">欧气攻略</View>
        </View>
      </View>
    );
  }

  /**
   * 欧气攻略弹框
   */
  handleStrategyModalShow = () => {
    this.handleModalShowAndHide('strategy', true);
  };

  /**
   * 渲染标题图片
   * @returns
   */
  renderTitleBj() {
    const {
      pics: {titleBj},
    } = this.state;
    return <Image src={titleBj} className="titleBj" />;
  }

  /**
   * 渲染开始游戏和操作（领福利、兑好礼、排行版）
   * @returns
   */
  renderStartGame() {
    const {pics} = this.state;
    const {
      main: {
        userInfo: {gameAvailableTimes},
      },
    } = this.props;

    return (
      <View className="gameMiddle">
        {/* 领取福利 */}
        <View className="propOperate" onClick={this.handlePropModalShow}>
          <Image src={pics.propBuffIcon} className="propIcon" />
          <View className="propTitle">魔力进阶</View>
        </View>

        {/* 兑好礼 */}
        <View className="exchangeOperate" onClick={this.handleExchangeGift}>
          <Image src={pics.exchangeIcon} className="operateIcon" />
          <View className="operateTitle">兑好礼</View>
        </View>

        <View className="gameOperate">
          <View className="timeShow">
            <View className="timeExtra">剩余次数:{gameAvailableTimes}次</View>
          </View>
          <View className="startGame" onClick={this.handlePlayGame}>
            <View className="gameStartExtra">开始游戏</View>
          </View>
        </View>

        <View className="taskOperate" onClick={this.handleTaskModalShow}>
          <Image src={pics.taskIcon} className="operateIcon" />
          <View className="operateTitle">领福利</View>
        </View>

        {/* 排行版 */}
        <View className="rankOperate" onClick={this.handleRankingModalShow}>
          <Image src={pics.rankingIcon} className="operateIcon" />
          <View className="operateTitle"> 排行榜</View>
        </View>
      </View>
    );
  }

  /**
   * 开始玩游戏
   */
  handlePlayGame = () => {
    const {
      main: {userInfo, gameInfo},
    } = this.props;

    console.log('goldCoinsIndex handePlayGame userInfo', userInfo);

    // 非会员
    if (!userInfo.accountType) {
      // 非新人
      if (userInfo.gameComputedTimes > 0) {
        this.handleModalShowAndHide('member', true);
        return;
      }
    }

    // 判断游戏次数是否够
    if (!userInfo.gameAvailableTimes) {
      Taro.showToast({
        title: '做任务获取次数吧~',
        icon: 'none',
      });
      return;
    }
    // 当日玩游戏次数
    if (!userInfo.userDailyTimes) {
      Taro.showToast({
        title: '今日游戏次数已达上限~',
        icon: 'none',
        duration: 2000,
      });
      return;
    }

    // 开始跳转开始游戏页面
    this.handleRedirectToGame();
  };

  /**
   * 领福利
   */
  handleTaskModalShow = () => {
    const {
      main: {userInfo},
    } = this.props;

    // 非会员不能做任务，让他开会员
    if (!userInfo.accountType) {
      this.handleModalShowAndHide('member', true);
    } else {
      this.handleModalShowAndHide('task', true);
    }
  };

  /**
   * 兑好礼
   */
  handleExchangeGift = () => {
    Taro.navigateTo({
      url: '/pages/package-I/goldCoinsExchange/index',
    });
  };

  /**
   * 魔力进阶（道具）
   */
  handlePropModalShow = () => {
    this.handleModalShowAndHide('propEffect', true);
  };

  /**
   * 排行榜单模态框弹出
   */
  handleRankingModalShow = () => {
    // this.handleModalShowAndHide('ranking', true);
    this.handleQueryRankingItems(); // 查询榜单信息
  };

  /**
   * 渲染会员弹框
   */
  renderMemberModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <MemberModal
        visible={visible && type == 'member'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        onActivate={() => this.handleActivateMember()}
      />
    );
  }

  /**
   * 模态框的弹出和隐藏
   */
  handleModalShowAndHide = (type, visible, item = null) => {
    this.setState({
      modal: {
        ...this.state.modal,
        type: visible ? type : '',
        visible,
        item,
      },
    });
  };

  /**
   * 确定开通会员
   */
  handleActivateMember = () => {
    this.handleModalShowAndHide('', false); // 关闭模态框
    // 跳转到开通会员界面
    Taro.navigateTo({
      url: '/pages/package-A/memberOpen/index',
    });
  };

  /**
   * 渲染魔力币获取模态框游戏任务
   */
  renderTaskModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <TaskModal
        visible={visible && type == 'task'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        onQueryTask={this.handleQueryTaskItems}
      />
    );
  }

  /**
   * 渲染攻略弹框
   */
  renderStrategyModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <StrategyModal visible={visible && type == 'strategy'} onCancel={() => this.handleModalShowAndHide('', false)} />
    );
  }

  /**
   * 渲染排行版
   */
  renderRankingModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <RankingModal visible={visible && type == 'ranking'} onCancel={() => this.handleModalShowAndHide('', false)} />
    );
  }

  /**
   * 渲染每日领取奖励
   * @returns
   */
  renderDailyExclusiveModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <DailyExclusiveModal
        visible={visible && type == 'dailyExclusive'}
        onCancel={this.handleCancelGameTimesDaily}
        onReceive={this.handleReceive}
      />
    );
  }

  /**
   * 点击开心收下
   */
  handleReceive = () => {
    console.log('index.tsx handleReceive');
    this.handleQueryGameTimesDaily(false); // 获取游戏次数
  };

  /**
   * 取消
   */
  handleCancelGameTimesDaily = () => {
    this.handleQueryGameTimesDaily(true); // 获取游戏次数
  };

  /**
   * 渲染道具模态框
   */
  renderPropModal() {
    const {
      modal: {visible, type, item},
      selectedProp,
    } = this.state;
    console.log('index.tsx renderPropModal selectdProp', selectedProp);

    return (
      <PropModal
        selectItem={selectedProp}
        visible={type == 'propEffect'}
        onCancel={(type) => this.handleCancelSelectProp(type)}
        onUse={this.handleUseSelectProp}
        onQueryProp={this.handleQueryPropItems}
      />
    );
  }

  /**
   * 选择道具
   */
  handleUseSelectProp = (data) => {
    console.log('index.tsx handleUseSelectProp data', data);
    this.setState({
      selectedProp: data,
    });
    this.handleModalShowAndHide('', false); // 关闭模态框
  };

  /**
   * 取消道具使用
   */
  handleCancelSelectProp = (type) => {
    // 取消选中就不关
    if (type != 'selectedCancel') {
      this.handleModalShowAndHide('', false); // 关闭模态框
    } else {
      this.setState({
        selectedProp: null,
      });
    }
  };

  /**
   * 重定向游戏
   */
  handleRedirectToGame = () => {
    const {query, selectedProp} = this.state;
    let url = '/pages/package-I/receiveGoldCoins/index';

    // 选择道具
    if (selectedProp && selectedProp.id) {
      let count = selectedProp.ruleType == PROP_TYPE['DOUBLE'] ? selectedProp.ruleValue : 0;
      url = url + '?propEffect=' + count + '&propId=' + selectedProp.id;
    }

    Taro.navigateTo({
      url,
    });
  };

  /**
   * 渲染广告模态框
   */
  renderAdvModal() {
    const {
      adModal: {imgUrl, isModalFlag, jumpPage},
    } = this.state;
    return (
      <AdvModal
        imgUrl={imgUrl}
        handleUrl={() => handleUrl(jumpPage)}
        handleClose={() => this.handleCloseAtModal()}
        isModalFlag={isModalFlag}
      />
    );
  }

  /**
   * 关闭广告模态框
   */
  handleCloseAtModal = () => {
    const {adModal} = this.state;

    this.setState(
      {
        adModal: {
          ...adModal,
          isModalFlag: false,
        },
      },
      async () => {
        if (this.state.adModal.nextPopupId) {
          await this.handleAdModalUpdateStatus(this.state.adModal.nextPopupId);
        }
      },
    );
  };

  /**
   * 广告弹出
   * @param id
   */
  async handleAdModalUpdateStatus(id) {
    const {adModal} = this.state;
    const res = await fetchModal(adModal.type);
    let popupId = null;
    if (!id && res && res.length > 0) {
      popupId = res[0].popupId;
    } else {
      popupId = id;
    }
    const flagParams = await setModalShow(res, adModal.type, popupId);

    this.setState(
      {
        adModal: {
          ...adModal,
          isModalFlag: flagParams.showFlag,
          imgUrl: flagParams.imgUrl,
          jumpPage: (flagParams.jumpPage && JSON.parse(flagParams.jumpPage)) || '',
          nextPopupId: flagParams.nextPopupId,
        },
      },
      () => {
        if (this.state.adModal.nextPopupId && !this.state.adModal.isModalFlag) {
          this.isGo(this.state.adModal.nextPopupId);
        }
      },
    );
  }
  async isGo(id) {
    await this.handleAdModalUpdateStatus(id);
  }

  /**
   * 分享好友
   * @param res
   * @returns
   */
  onShareAppMessage(res) {
    const {
      pics: {gameShareThum},
      query,
    } = this.state;

    if (query && query.taskConditionsType == TASK_CONDITION_TYPE['share']) {
      this.handleComputedTask(query);
    }
    console.log('选择iponShareAppMessage res.target', res.target);
    return {
      title: GAME_SHARE_TITLE,
      path: '/pages/package-I/home/index',
      imageUrl: gameShareThum,
      query: 'share=true',
    };
  }

  /**
   * 完成任务
   */
  handleComputedTask = (data) => {
    // 编辑参数
    let params = {
      id: data.taskId,
    };
    console.log('goldCoinsIndex params', params);
    this.props.actions.action.computedTask(params);
    this.setState({
      query: {
        ...this.state.query,
        taskId: '',
        taskConditionsType: '',
      },
    });
  };

  /**
   * 分享到朋友圈
   * @param res
   * @returns
   */
  onShareTimeline(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    console.log('选择iponShareAppMessage res.target', res.target);
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      path: '/pages/package-I/home/index',
      query: 'share=true',
    };
  }

  /**
   * 收藏
   * @param res
   * @returns
   */
  onAddToFavorites(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      query: 'favorite=true',
    };
  }
}
